import React, {
    Component,
} from 'react';
import {
    StyleSheet,
    Text,
    View,
    Platform,
    Dimensions,
    TouchableOpacity,
    Image,
    Alert,
    FlatList,
    TextInput,
    Linking,
    ScrollView,
    Switch,
    DeviceEventEmitter,
} from 'react-native';
import AndroidModule from 'src/utils/AndroidConnent'
import Loading from "../../../utils/Loading";
import HttpUtils from '../../../utils/HttpUtils';
import HttpUrls from '../../../utils/HttpUrls';
import Header from "../../../components/header";
import PublishCarArrow from '../publishCar/components/PublishCarArrow';
import PublishCarTextInput from '../publishCar/components/PublishCarTextInput';
import Constant from '../../../utils/Constant'//全局变量
import { ToastToUser } from '../../../utils/CustomToast';
import DatePickerPart from '../../../components/Tool/DatePickerPart'

let navigation
let maxCarConditionLength = 500

export default class CarBookPage extends Component {
    constructor(props) {
        super(props);
        let carId = this.props.route && this.props.route.params && this.props.route.params.carId ? this.props.route.params.carId : '';
        let isEdit = this.props.route && this.props.route.params && this.props.route.params.isEdit ? this.props.route.params.isEdit : false

        this.state = {
            isEdit,
            carId: carId,
            goodsType: 2,
            tradePrice: '',//成交价格
            downPayment: '',//定金
            saleType: 13,//销售类型
            saleTypes: [{ title: '零售', value: 13 }, { title: '批发', value: 14 }, , { title: '同行报车', value: 15 }],
            contractPic: '',//合同图片地址
            contractPdf: '',//合同pdf地址
            tradeDate: '',//预定日期
            sellerUserId: '',//销售员id
            sellerName: '', //销售员
            buyerName: '', //客户名称
            remarks: '', //备注

            dateTypeMode: 'YYYY-MM-DD',
            showDatePicker: false,
        }
    }

    componentDidMount() {
        this.uploadContract = DeviceEventEmitter.addListener('uploadContract', (result) => {
            this.setState({
                contractPic: result.contractPic,
                contractPdf: result.contractPdf,
            })
        })
        if (this.state.isEdit) {
            this.getCarOrderInfo()
        }
    }

    componentWillUnmount() {
        if (this.uploadContract) {
            this.uploadContract.remove()
        }
    }

    getCarOrderInfo() {
        if (this.Loading) {
            this.Loading.show();
        }
        let params = {
            carId: this.state.carId,
            saleStatus: 3, //车辆预定
        }
        HttpUtils.getRequest(HttpUrls.getCarOrder, params)
            .then((result) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
                if (result.code == 0) {
                    let data = result.data
                    this.setState({
                        goodsType: data.goodsType ? data.goodsType : 2,
                        tradePrice: data.tradePrice ? (data.tradePrice / 10000).toFixed(2).toString() : '',
                        downPayment: data.downPayment ? data.downPayment.toString() : '',
                        saleType: data.saleType ? data.saleType : '',
                        contractPic: data.contractPic,
                        contractPdf: data.contractPdf,
                        tradeDate: data.tradeDate,
                        sellerUserId: data.sellerUserId,
                        sellerName: data.sellerName,
                        buyerName: data.buyerName,
                        remarks: data.remarks,
                    })
                } else {
                    ToastToUser(result.msg ? result.msg : result.statusText)
                }
            })
            .catch((error) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
            });
    }

    render() {
        navigation = this.props.navigation;
        return (
            <View style={styles.container}>
                <Header navigation={navigation} Title={this.state.isEdit ? '编辑预定' : '车辆预定'}></Header>
                <ScrollView
                    style={{ flex: 1 }}
                >
                    <View style={styles.sepLine} />

                    <View style={styles.contentContainer}>
                        <PublishCarTextInput
                            name={'成交价格'}
                            necessary={true}
                            value={this.state.tradePrice}
                            unit={'万元'}
                            keyboardType={'decimal-pad'}
                            onChangeText={(value) => {
                                this.setState({
                                    tradePrice: value
                                })
                            }}
                        />
                        <PublishCarTextInput
                            name={'定金'}
                            necessary={true}
                            value={this.state.downPayment}
                            unit={'万元'}
                            keyboardType={'decimal-pad'}
                            onChangeText={(value) => {
                                this.setState({
                                    downPayment: value
                                })
                            }}
                        />
                        <View style={styles.saleTypeBox}>
                            <View style={styles.itemLeftBox}>
                                <Text style={styles.itemTitleText}>
                                    {'销售类型'}
                                    <Text style={{ color: '#FB3D3C' }}>*</Text>
                                </Text>
                            </View>
                            {
                                this.state.saleTypes.map((item, index) => {
                                    return (
                                        <TouchableOpacity
                                            style={this.state.saleType == item.value ? styles.selSaleItemBox : styles.saleItemBox}
                                            activeOpacity={this.state.isEdit ? 1 : 0.8}
                                            onPress={() => {
                                                if (!this.state.isEdit) {
                                                    this.setState({
                                                        saleType: item.value
                                                    })
                                                }
                                            }}
                                        >
                                            <Text style={styles.saleTypeText}>{item.title}</Text>
                                        </TouchableOpacity>
                                    )
                                })
                            }
                        </View>
                        <PublishCarArrow
                            name={'合同上传'}
                            necessary={true}
                            placeholder={'请上传合同'}
                            content={(this.state.contractPic || this.state.contractPdf) ? '已上传' : ''}
                            clickHandle={() => {
                                let params = {
                                    contractPic: this.state.contractPic,
                                    contractPdf: this.state.contractPdf
                                }
                                AndroidModule.selectContract(params, (error, result) => {
                                    this.setState({
                                        contractPic: result.contractPic,
                                        contractPdf: result.contractPdf,
                                    })
                                })
                            }}
                        />
                        <PublishCarArrow
                            name={'预定日期'}
                            necessary={true}
                            content={this.state.tradeDate}
                            clickHandle={() => {
                                this.setState({ showDatePicker: true })
                            }}
                        />
                        <PublishCarArrow
                            name={'销售员'}
                            necessary={true}
                            content={this.state.sellerName}
                            clickHandle={() => {
                                navigation.navigate('SellerSelectPage', {
                                    selectedUserId: this.state.sellerUserId,
                                    selectCompletion: (item) => {
                                        this.setState({
                                            sellerUserId: item.userId,
                                            sellerName: item.fullname
                                        })
                                        navigation.goBack()
                                    }
                                })
                            }}
                        />
                        <PublishCarTextInput
                            name={'客户名称'}
                            hideSepline={true}
                            value={this.state.buyerName}
                            onChangeText={(value) => {
                                this.setState({
                                    buyerName: value
                                })
                            }}
                        />

                    </View>

                    <View style={[styles.basicInfoContainer, { paddingVertical: 11 }]}>
                        <Text style={styles.baseText1}>备注</Text>
                        <View style={styles.descBg}>
                            <TextInput
                                autoCorrect={false}
                                editable={true}
                                multiline={true}
                                maxLength={maxCarConditionLength}
                                autoCapitalize='characters'
                                style={styles.textInput}
                                placeholder={'请输入车辆备注'}
                                placeholderTextColor="#999999"
                                value={this.state.remarks}
                                onChangeText={this.changeText.bind(this, 'remarks')}
                            />
                            <Text style={styles.lengthText}>{this.state.remarks.length + '/' + maxCarConditionLength}</Text>
                        </View>
                    </View>

                </ScrollView>

                <View style={[styles.bottomBox, {height: 60+Constant.bottomHeight}]}>
                    <TouchableOpacity
                        style={styles.submitBox}
                        activeOpacity={0.8}
                        onPress={() => {
                            this.submit()
                        }}
                    >
                        <Text style={styles.submitText}>提交</Text>
                    </TouchableOpacity>
                </View>

                <Loading onRef={(ref) => (this.Loading = ref)} />

                <DatePickerPart type={this.state.dateTypeMode} defaultDate={this.state[this.state.tradeDate]} show={this.state.showDatePicker} changeState={
                    (val) => { // 时间选择组件显示与否
                        this.setState({
                            showDatePicker: val,
                        })
                    }
                } changeDate={(date) => {
                    this.setState({
                        tradeDate: date,
                    })
                }} />

            </View>
        )
    }

    //输入框内容输入
    changeText(type, val) {
        this.setState({
            [type]: val
        })
    }

    submit() {
        if (!this.state.tradePrice) {
            ToastToUser('请输入成交价格')
            return
        }
        if (!this.state.downPayment) {
            ToastToUser('请输入定金')
            return
        }
        if (!this.state.saleType) {
            ToastToUser('请选择销售类型')
            return
        }
        if (!this.state.contractPic && !this.state.contractPdf) {
            ToastToUser('请上传合同')
            return
        }
        if (!this.state.tradeDate) {
            ToastToUser('请选择预定日期')
            return
        }
        if (!this.state.sellerUserId) {
            ToastToUser('请选择销售员')
            return
        }

        let params = {
            goodsId: this.state.carId,
            saleStatus: 3, //车辆预定
            goodsType: this.state.goodsType,
            tradePrice: this.state.tradePrice * 10000,
            downPayment: this.state.downPayment,
            saleType: this.state.saleType,
            contractPic: this.state.contractPic,
            contractPdf: this.state.contractPdf,
            tradeDate: this.state.tradeDate,
            sellerUserId: this.state.sellerUserId,
            sellerName: this.state.sellerName,
            buyerName: this.state.buyerName,
            remarks: this.state.remarks,
        }

        let url = ''
        if (this.state.isEdit) {
            url = HttpUrls.editCarOrder
        } else {
            url = HttpUrls.addCarOrder
        }

        if (this.Loading) {
            this.Loading.show('提交中...');
        }
        HttpUtils.postRequest(HttpUrls.addCarOrder, params)
            .then((result) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
                if (result.code == 0) {
                    ToastToUser('提交成功!')
                    if (this.props.route.params && this.props.route.params.completion) {
                        setTimeout(() => {
                            this.props.route.params.completion()
                        }, 500);
                    }
                } else {
                    ToastToUser(result.msg ? result.msg : result.statusText)
                }
            })
            .catch((error) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
            });

    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F9F9F9',
    },
    sepLine: {
        width: '100%',
        height: 10
    },
    contentContainer: {
        width: '100%',
        flexDirection: 'column',
        backgroundColor: '#fff',
        paddingHorizontal: 16,

    },
    saleTypeBox: {
        flexDirection: 'row',
        alignItems: 'center',
        width: '100%',
        height: 45,
        borderBottomColor: '#e4e4e4',
        borderBottomWidth: 0.3,
    },
    itemLeftBox: {
        width: 96,
    },
    itemRightBox: {
        flex: 1,
        height: '100%',
        marginLeft: 4,
        flexDirection: 'row',
        justifyContent: 'flex-start',
        alignItems: 'center'
    },
    itemTitleText: {
        lineHeight: 19,
        fontSize: 14,
        color: '#222222'
    },
    saleItemBox: {
        marginRight: 12,
        width: 64,
        height: 24,
        justifyContent: 'center',
        alignItems: 'center',
        borderRadius: 3,
        borderWidth: 1,
        borderColor: '#E5E5E5'
    },
    selSaleItemBox: {
        marginRight: 12,
        width: 64,
        height: 24,
        justifyContent: 'center',
        alignItems: 'center',
        borderRadius: 3,
        borderWidth: 1,
        borderColor: '#FFDE00',
        backgroundColor: 'rgba(255,222,0,0.1)'
    },
    saleTypeText: {
        color: '#333',
        fontSize: 12
    },
    basicInfoContainer: {
        marginTop: 10,
        width: '100%',
        flexDirection: 'column',
        paddingHorizontal: 15,
        paddingTop: 14,
        backgroundColor: '#fff'
    },
    baseText: {
        fontSize: 15,
        fontWeight: '500',
        color: '#222222',
        marginBottom: 11,
    },
    baseText1: {
        fontSize: 14,
        fontWeight: '500',
        color: '#333',
        marginBottom: 13,
    },
    descBg: {
        width: '100%',
        height: 123,
        paddingHorizontal: 10,
        paddingTop: 4,
        paddingBottom: 17,
        backgroundColor: '#F9F9F9',
        borderRadius: 6
    },
    textInput: {
        color: '#333333',
        fontSize: 14,
        flex: 1,
        textAlignVertical: 'top',
        lineHeight: 18,
    },
    lengthText: {
        position: 'absolute',
        bottom: 5,
        right: 8,
        color: '#999999',
        fontSize: 12
    },
    bottomBox: {
        backgroundColor: '#fff',
        width: '100%',
        paddingTop: 7,
        paddingHorizontal: 15,
        flexDirection: 'column',
        alignItems: 'center'
    },
    submitBox: {
        width: '100%',
        height: 46,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#FFE000',
        borderRadius: 23
    },
    submitText: {
        color: '#333333',
        fontSize: 16
    }

})